package com.mmm.station.activiti.controller;


import com.mmm.station.activiti.entity.CompleteBean;
import com.mmm.station.activiti.entity.SysLeave;
import com.mmm.station.activiti.entity.WorkflowBean;
import com.mmm.station.activiti.service.WorkflowService;
import com.mmm.station.base.controller.BaseController;
import com.mmm.station.base.entity.BaseResult;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "workfolw")
public class WorkflowController extends BaseController {



	@Autowired
	private WorkflowService workflowService;
	


	/**
	 * 查看部署的流程
	 * @return
	 */
	@RequestMapping(value = "findProcess")
	@ResponseBody
	public Object findProcessDefinition(){

		List<WorkflowBean> list=workflowService.findProcessDefinition();
		return new BaseResult(true,list);
	}
	
	/**
	 * 发布流程
	 * @return
	 */
	@RequestMapping(value = "newdeploy")
	@ResponseBody
	public Object newdeploy(MultipartFile file){
		try{
			int a = workflowService.newdeploy(file);
			return new BaseResult(true,"部署成功");
		}catch (Exception e){
			logger.error("流程部署",e);
			return new BaseResult(false,"部署失败");
		}

	}
	
	/**
	 * 删除部署信息
	 */
	@RequestMapping(value = "delDeployment")
	@ResponseBody
	public Object delDeployment(String deploymentId){
		workflowService.deleteProcessDefinition(deploymentId);
		return new BaseResult(true,"删除成功");
	}

	/**
	 * 查看流程图
	 * @throws Exception
	 */
	@RequestMapping(value = "viewImage")
	public String viewImage(String deploymentId, HttpServletResponse response, String imageName) throws Exception{
		//1：获取页面传递的部署对象ID和资源图片名称
		//资源图片名称
		//2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
		InputStream in = workflowService.findImageInputStream(deploymentId,imageName);
		//3：从response对象获取输出流
		OutputStream out = response.getOutputStream();
		//4：将输入流中的数据读取出来，写到输出流中
		for(int b=-1;(b=in.read())!=-1;){
			out.write(b);
		}
		out.close();
		in.close();
		//将图写到页面上，用输出流写
		return null;
	}

	/** 启动流程
	 *
	 * @param userName
	 * @return
     */
//	@RequestMapping(value = "startProcess")
//	@ResponseBody
//	public Object startProcess(String processKey, SysLeave sysLeave){
//		sysLeave.setSysUserId(ShiroUtils.getCurrentUser().getSysUserId());
//		sysLeave.setState((long)0);
//		workflowService.saveStartProcess(processKey,sysLeave);
//		return new BaseResult(true,"启动成功");
//	}


	/**
	 *查看任务
	 * @param userName
	 * @return
	 */
	@RequestMapping(value = "lookTask")
	@ResponseBody
	public Object lookTask(){

		return new BaseResult(true,workflowService.findTaskListByName());
	}

	/**
	 *完成任务
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "complete")
	@ResponseBody
	public Object completeTask(CompleteBean completeBean){

		workflowService.saveSubmitTask(completeBean);
		return new BaseResult(true,"我的工作完成");
	}


	/**
	 *查看历史
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "lookHi")
	@ResponseBody
	public Object lookHi(SysLeave sysLeave){
		logger.info("查看历史");
		String businessKey = sysLeave.getClass().getSimpleName()+"."+sysLeave.getSysLeaveId();

		return new BaseResult(true,workflowService.findComment(businessKey));
	}

	/**
	 * 任务管理首页显示
	 * @return
	 */
	public String listTask(){
//		//1：从Session中获取当前用户名
//		String name = SessionContext.get().getName();
//		//2：使用当前用户名查询正在执行的任务表，获取当前任务的集合List<Task>
//		List<Task> list = workflowService.findTaskListByName(name);
//		ValueContext.putValueContext("list", list);
		return "task";
	}
	
	/**
	 * 打开任务表单
	 */
	public String viewTaskForm(){
//		//任务ID
//		String taskId = workflowBean.getTaskId();
//		//获取任务表单中任务节点的url连接
//		String url = workflowService.findTaskFormKeyByTaskId(taskId);
//		url += "?taskId="+taskId;
//		ValueContext.putValueContext("url", url);
		return "viewTaskForm";
	}
	
	// 准备表单数据
	public String audit(){
		//获取任务ID
//		String taskId = workflowBean.getTaskId();
//		/**一：使用任务ID，查找请假单ID，从而获取请假单信息*/
//		LeaveBill leaveBill = workflowService.findLeaveBillByTaskId(taskId);
//		ValueContext.putValueStack(leaveBill);
//		/**二：已知任务ID，查询ProcessDefinitionEntiy对象，从而获取当前任务完成之后的连线名称，并放置到List<String>集合中*/
//		List<String> outcomeList = workflowService.findOutComeListByTaskId(taskId);
//		ValueContext.putValueContext("outcomeList", outcomeList);
//		/**三：查询所有历史审核人的审核信息，帮助当前人完成审核，返回List<Comment>*/
//		List<Comment> commentList = workflowService.findCommentByTaskId(taskId);
//		ValueContext.putValueContext("commentList", commentList);
		return "taskForm";
	}
	
	/**
	 * 提交任务
	 */
	public String submitTask(){
//		workflowService.saveSubmitTask(workflowBean);
		return "listTask";
	}
	
	/**
	 * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
	 */
	@RequestMapping(value = "viewCurrentImage")
	@ResponseBody
	public Object viewCurrentImage(SysLeave sysLeave){

		String businessKey = sysLeave.getClass().getSimpleName()+"."+sysLeave.getSysLeaveId();
		String taskId = workflowService.getTaskByBusinessKey(businessKey).getId();
		/**一：查看流程图*/
		//1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
		ProcessDefinition pd = workflowService.findProcessDefinitionByTaskId(taskId);
		//workflowAction_viewImage?deploymentId=<s:property value='#deploymentId'/>&imageName=<s:property value='#imageName'/>
		Map map = new HashMap();
		map.put("deploymentId", pd.getDeploymentId());
		map.put("imageName", pd.getDiagramResourceName());
		/**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
		Map<String, Object> imagemap = workflowService.findCoordingByTask(taskId);
		map.put("imageMap",imagemap);
		return new BaseResult(true,map);
	}
	
	// 查看历史的批注信息
	public String viewHisComment(){
		//获取清单ID
//		Long id = workflowBean.getId();
//		//1：使用请假单ID，查询请假单对象，将对象放置到栈顶，支持表单回显
//		LeaveBill leaveBill = leaveBillService.findLeaveBillById(id);
//		ValueContext.putValueStack(leaveBill);
//		//2：使用请假单ID，查询历史的批注信息
//		List<Comment> commentList = workflowService.findCommentByLeaveBillId(id);
//		ValueContext.putValueContext("commentList", commentList);
		return "viewHisComment";
	}
}
